<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>超时与取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
</head>
<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        //获取按钮
        let btns = document.querySelectorAll('button');
        let xhr;
        //给第一个按钮绑定事件
        btns[0].onclick = _.debounce(function(){
            xhr = new XMLHttpRequest();
            //设置请求的超时时间
            xhr.timeout = 3000;
            // timeout 事件
            xhr.ontimeout = function(){
                console.log('请求超时, 请稍后再试~~');
            }
            xhr.open('get','http://127.0.0.1/delay-server');
            xhr.send();
            xhr.onload = function(){
                console.log(xhr.response);
            }
        }, 1000);

        btns[1].onclick = function(){
            //主动取消 AJAX 请求
            xhr.abort();
        }
    </script>
</body>
</html>